//
//  NSString+Trim.h
//  collection
//
//  Created by ZHANG Tianle on 12/7/11.
//  Copyright (c) 2011 collection. Inc.. All rights reserved.
//

#ifndef collection_NSString_Trim_h
#define collection_NSString_Trim_h

@interface NSString (TrimmingAdditions)

- (NSString *) stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet;
- (NSString *) stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet;

@end


@implementation NSString (TrimmingAdditions)

- (NSString *) stringByTrimmingLeadingCharactersInSet:(NSCharacterSet *)characterSet 
{
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];    
    [self getCharacters:charBuffer];
    
    for (location = 0; location < length; location++) {
        if (![characterSet characterIsMember:charBuffer[location]]) {
            break;
        }
    }
    
    return [self substringWithRange:NSMakeRange(location, length - location)];
}

- (NSString *) stringByTrimmingTrailingCharactersInSet:(NSCharacterSet *)characterSet 
{
    NSUInteger location = 0;
    NSUInteger length = [self length];
    unichar charBuffer[length];    
    [self getCharacters:charBuffer];
    
    for (length = 0; length > 0; length--) {
        if (![characterSet characterIsMember:charBuffer[length - 1]]) {
            break;
        }
    }
    
    return [self substringWithRange:NSMakeRange(location, length - location)];
}

@end

#endif
